package projectsys.core.global.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import projectsys.core.global.service.LoginManager;
import projectsys.core.utils.DateUtils;
import projectsys.core.utils.IPUtils;
import projectsys.core.utils.ToolUtils;
import projectsys.core.utils.UID;
import projectsys.core.utils.encrypt.EncryptUtil;
import projectsys.core.webutils.Constans;
import projectsys.sys.core.model.Role;
import projectsys.sys.core.model.User;
import projectsys.sys.core.model.UserDetail;
import projectsys.sys.core.service.ModuleManager;
import projectsys.sys.core.service.RoleManager;
import projectsys.sys.core.service.UserDetailManager;
import projectsys.sys.core.web.controller.BaseController;

@Controller
@RequestMapping("/sys/global/")
@SuppressWarnings({ "unchecked", "static-access", "rawtypes", "unused" })
public class LoginController extends BaseController{
	
	@Autowired
	LoginManager loginManager;
	@Autowired
	UserDetailManager userDetailManager;
	@Autowired
	RoleManager roleManager;
	@Autowired
	ModuleManager moduleManager;
	
	@RequestMapping("index")
	public ModelAndView index(HttpServletRequest request) {
		return new ModelAndView();
	}
	
	/**
	 * 登录页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("login")
	public ModelAndView toHome(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("qbpt/login");
		Map<String, String> map =super.getParamSearchValue(request);
		mav.addObject("map", map);
		return mav;
	}
	
	/**
	 * 登录验证
	 * @param response
	 * @param request
	 */
	@RequestMapping("validateUser")
	public void validateUser(HttpServletResponse response,HttpServletRequest request){
		String sign = "4";
		IPUtils ipUtil=new IPUtils();
		String login_ip=ipUtil.getIPAddress(request);
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		try {
			password = EncryptUtil.md5(password);  //密码加密
		} catch (Exception e) {
		}
		String moduleSign = request.getParameter("moduleSign");  //获取标记
		Map map = new HashMap();
		map.put("username",username.toLowerCase());
		map.put("sfzh","");
		List listuser = loginManager.queryUserInfo(map);
		if(listuser.size()<=0){
			sign = "1";//用户不存在
		}else{
			Map mapuser = (Map)listuser.get(0);
			if(!ToolUtils.getValue(mapuser, "password").equals(password)){
				sign="2";//用户密码不正确
			}else{
				if(!ToolUtils.getValue(mapuser, "status").equals("01")){
					sign="3";//用户已被禁用
				}else{
					if(moduleSign.equals("first")){//如果是登录大首页则无需验证是否有权限
						sign = "5";//用户登录成功
					}else{
						Map map1 = new HashMap();
						map1.put("gjz",moduleSign);
						map1.put("username",username);
						List listpro = loginManager.queryPopedom(map1);
						
						if(listpro.size()<=0){
							sign = "4";//用户没有权限
						}else{
							sign = "5";//用户登录成功
						}
					}
				}
			}
		}
		if(sign.equals("5")){
			//插入登入日志
			Map mapuser1 = (Map)listuser.get(0);
//				map = insertUserLoginLog(map, mapuser1, sign, username, login_ip, "01");//把获取的信息添加到Map中
		}
		ToolUtils.queryValidate(sign, response);
	}
	
	/**
	 * 登录成功跳转
	 * @param response
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("loginSuccessBh")
	public ModelAndView loginSuccessBh(HttpServletResponse response,HttpServletRequest request,HttpSession session){
		String username = request.getParameter("login_id");
		String password = request.getParameter("password");
		//获取当前用户信息
		User userm = Usermessage(username, password);
		//获取当前用户权限
		Map poMap = popedom(username, userm);
		//获取当前用户角色信息
		Map roleMap = role(username,password);
		session.setAttribute("userm", userm);
		session.setAttribute("popedom", poMap);
		session.setAttribute("role", roleMap);
		
		Map log = new HashMap();
		log.put("id",new UID().getRandomID());
		log.put("username",userm.getAccount());
		log.put("sfzh",userm.getIdnumber());
		log.put("dept_name",userm.getDept_name());
		log.put("dept_code",userm.getDept_code());
//		log.put("station_name",userm.getStation_name());
//		log.put("station_code",userm.getStation_code());
		log.put("ip",request.getRemoteAddr());
		log.put("time",DateUtils.getCurrentTimeAs14String());
		log.put("module_sign","first");
		System.out.println("用户："+userm.getAccount()+"("+userm.getName()+";机器IP："+request.getRemoteAddr()+";登录时间："+DateUtils.getCurrentTimeAs14String()+"进入系统");
		loginManager.insertUserLog(log);
		//重定向至首页
		ModelAndView mav = new ModelAndView(new RedirectView(request.getContextPath()+"/sys/global/to_index.xhtml"));
		
		return mav;
	}
	
	/**
	 * 组装用户信息装入session
	 * @param username
	 * @param password
	 * @return
	 */
	public User Usermessage(String username,String password){
		Map map = new HashMap();
		map.put("username", username == null ? username : username.toLowerCase());
		map.put("sfzh","");
		//查询当前用户信息
		List listuser = loginManager.queryUserInfo(map);
		Map umap = (Map)listuser.get(0);
		User user = new User();
		user.setAccount(ToolUtils.getValue(umap, "account"));
		user.setDept_code(ToolUtils.getValue(umap, "dept_code"));
		user.setDept_name(ToolUtils.getValue(umap, "dept_name"));
		user.setId(ToolUtils.getValue(umap, "id"));
		user.setIdnumber(ToolUtils.getValue(umap, "sfzh"));
		user.setName(password);
		user.setRegdate(ToolUtils.getValue(umap, "regdate"));
		user.setStatus(ToolUtils.getValue(umap, "status"));
		
		UserDetail userDetail = this.userDetailManager.getUserDetailByid(user.getId());
		user.setUserDetail(userDetail);
		
		List<Role> userRole = this.roleManager.selectRoleByUserId(user.getId());
		user.setRoles(userRole);
		
		return user;
	}
	
	/**
	 * 登录成功
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws IOException
	 */
	public ModelAndView to_index(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
		ModelAndView mav = new ModelAndView("/normal/home/index");
		Map<String,String> map = super.getParamValues(request);
		User user = (User) request.getSession().getAttribute("userm");
		if(user == null) {
			response.sendRedirect(request.getContextPath() + "/sys/global/login.xhtml");
		}
		try {
			String sysMenu = this.moduleManager.getMainMenuPro(new String[]{"QTXTGL"}, user);
			mav.addObject("sysMenu", sysMenu);
			mav.addObject("map", map);
		}catch(Exception e) {
			throw new RuntimeException("401");
		}
		return mav;
	}
	
	/**
	 * 查询用户对应的权限信息
	 * @param username
	 * @param user
	 * @return
	 */
	public Map popedom(String username,User user){
		Map map = new HashMap();
		map.put("username", username);
		map.put("sfzh", "");
		Set<String> paths = new HashSet<String>();
		paths.addAll(Constans.notCheckUri);
		//查询用户的权限信息
		List poList = loginManager.queryPopedom(map);
		Map poMap = new HashMap();
		for(int i=0; i<poList.size(); i++) {
			Map m = (Map)poList.get(i);
			m.put(ToolUtils.getValue(m, "code"),ToolUtils.getValue(m, "id"));
			String path = ToolUtils.getValue(m, "path");
			if(path != null) {
				if (path.indexOf("?") > 0) {
					paths.add(path.substring(0, path.indexOf("?"))
							.toLowerCase());
				} else
					paths.add(path.toLowerCase());
			}
		}
		user.setPaths(paths);
		return poMap;
	}
	/**
	 * 查询用户所有角色信息
	 * @param username
	 * @param password
	 * @return
	 */
	public Map role(String username,String password){
		Map map = new HashMap();
		map.put("username", username);
		map.put("sfzh", "");
		Map roleMap = new HashMap();
		List<Map> roleList = loginManager.getUserRole(map);
		if(roleList != null && roleList.size() > 0) {
			for(int i = 0; i<roleList.size(); i++) {
				Map m = roleList.get(i);
				roleMap.put(m.get("ROLECODE"), m.get("ROLECODE"));
			}
		}
		return roleMap;
	}
}











